#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
项目API控制器
处理项目相关的HTTP请求
"""

from flask import Blueprint, request, jsonify
from services.project_service import ProjectService
from database.mysql_manager import mysql_manager
from utils.validators import validate_project_data
from utils.response_helper import success_response, error_response, paginated_response

# 创建蓝图
project_bp = Blueprint('project', __name__, url_prefix='/api/projects')

# 初始化服务
def get_project_service():
    """获取项目服务实例"""
    db_session = mysql_manager.get_session()
    return ProjectService(db_session)


@project_bp.route('', methods=['GET'])
def get_projects():
    """
    获取项目列表
    
    GET /api/projects?page=1&per_page=10&search=keyword
    """
    try:
        # 获取查询参数
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
        search = request.args.get('search', '')
        
        # 获取项目列表
        project_service = get_project_service()
        result = project_service.get_projects(page, per_page, search)
        
        if result['success']:
            return paginated_response(
                data=result['projects'],
                page=page,
                per_page=per_page,
                total=result['total'],
                message='Projects retrieved successfully'
            )
        else:
            return error_response(result['message'], 500)
            
    except Exception as e:
        return error_response(f'Error fetching projects: {str(e)}', 500)


@project_bp.route('', methods=['POST'])
def create_project():
    """
    创建新项目
    
    POST /api/projects
    {
        "name": "string",
        "description": "string",
        "created_by": "string"
    }
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        # 验证数据
        validation_result = validate_project_data(data)
        if not validation_result['valid']:
            return error_response(validation_result['message'], 400)
        
        # 创建项目
        project_service = get_project_service()
        result = project_service.create_project(data)
        
        if result['success']:
            return success_response(
                data={'project_id': result['project_id']},
                message=result['message']
            )
        else:
            return error_response(result['message'], 400)
            
    except Exception as e:
        return error_response(f'Error creating project: {str(e)}', 500)


@project_bp.route('/<project_id>', methods=['GET'])
def get_project(project_id):
    """
    获取项目详情
    
    GET /api/projects/{project_id}
    """
    try:
        project_service = get_project_service()
        result = project_service.get_project_by_id(project_id)
        
        if result['success']:
            return success_response(
                data=result['project'],
                message='Project retrieved successfully'
            )
        else:
            return error_response(result['message'], 404)
            
    except Exception as e:
        return error_response(f'Error fetching project: {str(e)}', 500)


@project_bp.route('/<project_id>', methods=['PUT'])
def update_project(project_id):
    """
    更新项目信息
    
    PUT /api/projects/{project_id}
    {
        "name": "string",
        "description": "string",
        "status": "string"
    }
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        # 更新项目
        project_service = get_project_service()
        result = project_service.update_project(project_id, data)
        
        if result['success']:
            return success_response(
                message=result['message']
            )
        else:
            return error_response(result['message'], 404 if 'not found' in result['message'] else 400)
            
    except Exception as e:
        return error_response(f'Error updating project: {str(e)}', 500)


@project_bp.route('/<project_id>', methods=['DELETE'])
def delete_project(project_id):
    """
    删除项目
    
    DELETE /api/projects/{project_id}
    """
    try:
        project_service = get_project_service()
        result = project_service.delete_project(project_id)
        
        if result['success']:
            return success_response(
                message=result['message']
            )
        else:
            return error_response(result['message'], 404)
            
    except Exception as e:
        return error_response(f'Error deleting project: {str(e)}', 500)


@project_bp.route('/statistics', methods=['GET'])
def get_statistics():
    """
    获取项目统计信息
    
    GET /api/projects/statistics
    """
    try:
        project_service = get_project_service()
        result = project_service.get_statistics()
        
        if result['success']:
            return success_response(
                data=result['statistics'],
                message='Statistics retrieved successfully'
            )
        else:
            return error_response(result['message'], 500)
            
    except Exception as e:
        return error_response(f'Error fetching statistics: {str(e)}', 500)